package lsl.leetCode.test1216;

/**
 * 67.二进制求和
 * description:给你两个二进制字符串 a 和 b,以二进制字符串的形式返回它们的和。
 *
 * @author: liushengli
 * data: 2022/12/16
 */
public class test67 {
    public static void main(String[] args) {
        System.out.println(addBinary("1010", "1011"));
    }

    public static String addBinary(String a, String b) {
        StringBuilder result = new StringBuilder();
        int i = a.length() - 1;
        int j = b.length() - 1;
        int carry = 0;
        while (i >= 0 || j >= 0) {
            int x = i >= 0 ? a.charAt(i--) - '0' : 0;
            int y = j >= 0 ? b.charAt(j--) - '0' : 0;
            int sum = x + y + carry;
            carry = sum >= 2 ? 1 : 0;
            sum = sum >= 2 ? sum - 2 : sum;
            result.append(sum);
        }

        if (carry == 1) {
            result.append(1);
        }
        return result.reverse().toString();
    }
}
